#include "measuretime.h"

#include <qdebug.h>
//#include <QCoreApplication>
//#include <iostream>
//#include <sched.h>
#include <stdio.h>
#include <string.h>
//#include <sys/mman.h>
//#include <native/task.h>
//#include <native/timer.h>
//#include <rtdk.h>

using namespace std;

MeasureTime::MeasureTime(QString measureComment, int isPrint,  int printInterval, int measureCount)
{
    this->measureComment=measureComment;
    this->isPrint=isPrint;
    this->printInterval=printInterval;
    this->measureCount=measureCount;
    callCount=0;
    minTime=1000000000;
    maxTime=0;
    printCount=0;
    isPeriodTimeInitialed=0;

     qDebug()<<measureComment<<"isPrint="<<isPrint<<"printInverval="<<printInterval<<"measureCount"<<measureCount;


}
void MeasureTime::reset()
{
    callCount=0;
    addTime=0;
    minTime=1000000000;
    maxTime=0;
}

void MeasureTime:: recordInTime()
{
     clock_gettime(CLOCK_REALTIME, &inTime);
}

int MeasureTime:: recordOutTime()
{
      callCount++;
     clock_gettime(CLOCK_REALTIME, &outTime);
     int time;
      time=outTime.tv_nsec+1000000000*outTime.tv_sec-inTime.tv_nsec-1000000000*inTime.tv_sec;
    maxTime=max(maxTime,time);
    minTime=min(minTime,time);//time;//
    addTime+=time;
    averageTime=addTime/callCount;

    if(callCount>=measureCount)
    {
        printCount++;
        if( printCount==printInterval )
        {
            sprintf(printf_str,"%s:now=%d,max=%d,average=%f\n",measureComment.data(),time/1000, maxTime/1000, averageTime/1000);
            printfString=QString(printf_str);

            if( 1==isPrint ){
                qDebug()<<measureComment
                       <<"\t (units is us)"
                      <<"\t now="<<time/1000
                     <<"\t max="<<maxTime/1000
                    <<"\t average="<<averageTime/1000;
            }
            printCount=0;
        }

        callCount=0;
        addTime=0;
    }

    return time;
}

void MeasureTime::recordPeirodTime()
{
    if(isPeriodTimeInitialed==0)
    {
        isPeriodTimeInitialed=1;
        recordInTime();
    }
    else
    {
        recordOutTime();
       // inTime.tv_nsec=outTime.tv_nsec;
       // inTime.tv_sec=outTime.tv_sec;
        inTime=outTime;

    }
}
